package com.xwltz.core.utils.web;

import cn.hutool.core.net.NetUtil;
import com.xwltz.core.constants.FrameworkConfig;
import com.xwltz.core.utils.StringUtils;
import com.xwltz.core.utils.json.JsonUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @description 获取地址类
 * @information on version 1.0 be created by xwltz at 2021/12/28 11:00
 */

@Slf4j
public class AddressUtils {

	// IP地址查询
	public static final String IP_URL = "https://whois.pconline.com.cn/ipJson.jsp";

	// 未知地址
	public static final String UNKNOWN = "XX XX";

	public static String getRealAddressByIP(String ip) {
		String address = UNKNOWN;
		if (StringUtils.isBlank(ip)) {
			return address;
		}
		// 内网不查询
		ip = "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : HtmlUtil.cleanHtmlTag(ip);
		if (NetUtil.isInnerIP(ip)) {
			return "内网IP";
		}
		if (FrameworkConfig.isAddressEnabled()) {
			try {
				// 接入其它 HTTP 客户端
				String rspStr = "";

				if (StringUtils.isEmpty(rspStr)) {
					log.error("获取地理位置异常 {}", ip);
					return UNKNOWN;
				}
				Map<String, String> obj = JsonUtils.parseMap(rspStr);
				assert obj != null;
				String region = obj.get("pro");
				String city = obj.get("city");
				return String.format("%s %s", region, city);
			} catch (Exception e) {
				log.error("获取地理位置异常 {}", ip);
			}
		}
		return address;
	}
}
